package org.sixdog.mcsit.controller;

import com.alibaba.fastjson.JSON;
import org.sixdog.mcsit.po.User;
import org.sixdog.mcsit.service.CaptchaService;
import org.sixdog.mcsit.service.HttpService;
import org.sixdog.mcsit.service.TokenService;
import org.sixdog.mcsit.service.impl.UserServiceImpl;
import org.sixdog.mcsit.utils.HttpResult;
import org.sixdog.mcsit.utils.StringUtils;
import org.sixdog.mcsit.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private HttpService httpService;

    @PostMapping("/registerEmail")
    public Object registerEmail(HttpServletRequest request){
        String email = request.getParameter("email");
        String captchaValue = request.getParameter("captchaValue");
        if (captchaService.equalsCaptcha(email,captchaValue) && !StringUtils.isBlank(email,captchaValue)){
            User user = new User();
            user.setEmail(email);
            List<User> users = userService.selectUsers(user, 1, 10);
            for (User useri: users) {
                if (useri.getStatus()>0){
                    return  HttpResult.build(HttpResult.WRONG_REQUEST,"此邮箱已被注册");
                }
            }
            user.setIp(StringUtils.getRequestIp(request));
            if (users.size()>0){
                userService.updateUserByEmail(user);
            }else {
                userService.insterUser(user);
            }

            String registerToken = UUID.randomUUID().toString();
            tokenService.addToken(registerToken, email, 60);
            Map<String,Object> resultDate = new HashMap<>();
            resultDate.put("registerToken",registerToken);
            return HttpResult.build(HttpResult.SUCCESS_CODE,resultDate,"邮箱注册成功");

        }
        return HttpResult.build(HttpResult.WRONG_REQUEST,"验证码错误");
    }

    @PostMapping("/registerUser")
    public Object registerUser(HttpServletRequest request){
        User user = JSON.parseObject(request.getParameter("user"),User.class);
        String registerToken = request.getParameter("registerToken");
        String tokenValue = tokenService.getTokenValue(registerToken);
        if (!StringUtils.isBlank(user.getEmail(),tokenValue) && user.getEmail().equals(tokenValue)){
            user.setStatus(1);
            userService.updateUserByEmail(user);
            return HttpResult.build(HttpResult.SUCCESS_CODE,"注册成功");
        }
        return HttpResult.build(HttpResult.ERROR_CODE,"注册失败");
    }
    @PostMapping("/loging")
    public Object loging(HttpServletRequest request){
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String captchaKey = request.getParameter("captchaKey");
        String captchaValue = request.getParameter("captchaValue");

        if (StringUtils.isBlank(email,password,captchaValue,captchaKey)){
            return HttpResult.build(HttpResult.WRONG_REQUEST,"请求错误，检查参数");
        }
        if (!captchaService.equalsCaptcha(captchaKey, captchaValue)){
            return HttpResult.build(HttpResult.WRONG_REQUEST,"请求错误，检查验证码");
        }
        User user = userService.UserLogin(email, password);
        if (user==null){
            return HttpResult.build(HttpResult.WRONG_REQUEST,"请求错误，检查账号密码");
        }
        String token = UUID.randomUUID().toString();
        long timeMinute = 10080;
        boolean addTokenSuccess = tokenService.addToken(token, user.getUid(), timeMinute);
        if (!addTokenSuccess){
            return HttpResult.build(HttpResult.ERROR_CODE,"服务器错误");
        }
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("token",token);
        resultData.put("user",user);
        resultData.put("overdueTime", TimeUtils.longToDate((new Date()).getTime() + timeMinute*60*1000));

        return HttpResult.build(HttpResult.SUCCESS_CODE,resultData,"登录成功");
    }
    @PostMapping("/getCaptcha")
    public Object getCaptcha(HttpServletRequest request){
        String captchaType = request.getParameter("captchaType");
        if (CaptchaService.DEFAULT_TYPE.equals(captchaType)){
            Map<String, String> resultData = captchaService.buildCaptcha(captchaType, null);
            if (resultData!=null) return HttpResult.build(HttpResult.SUCCESS_CODE,resultData,"验证码获取成功");
        }
        String email = request.getParameter("email");
        //得到ip
        String ip = StringUtils.getRequestIp(request);

        if (CaptchaService.EMAIL_TYPE.equals(captchaType) && !StringUtils.isBlank(email,ip)){


            //请求频次验证
            long captchaEmailTime = captchaService.getCaptchaTimeByKey(email);
            long captchaIpTime = captchaService.getCaptchaTimeByKey(ip);
            if (captchaEmailTime>540 || captchaIpTime>0){
                return HttpResult.build(HttpResult.WRONG_REQUEST,captchaEmailTime,"请求频繁，请等待"+(captchaIpTime)+"秒后重试");
            }
            //邮箱验证
            String check = "^\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            if (!matcher.matches()){
                return HttpResult.build(HttpResult.WRONG_REQUEST,"邮箱格式错误");
            }

            Map<String,String> args = new HashMap<>();
            args.put("email",email);
            args.put("ip",ip);
            Map<String, String> resultData = captchaService.buildCaptcha(captchaType, args);
            if (resultData!=null) return HttpResult.build(HttpResult.SUCCESS_CODE,resultData,"验证码获取成功,请检查邮箱");
        }
        return HttpResult.build(HttpResult.ERROR_CODE,"获取失败");
    }

    @PostMapping("/getUserInfo")
    public Object getSuatus(HttpServletRequest request){
        String tokenKey = request.getHeader("mcsittoken");
        String uid = tokenService.getTokenValue(tokenKey);
        if (!StringUtils.isBlank(uid,tokenKey)){
            User user = userService.selectUserByUid(uid);
            if(user!=null){
                user.setPassword(null);
                Map<String,Object> resultData = new HashMap<>();
                resultData.put("user",user);
                return HttpResult.build(HttpResult.SUCCESS_CODE,resultData,"获取成功");
            }
        }
        return HttpResult.build(HttpResult.ERROR_CODE,"获取失败");
    }

    //未测试
    @GetMapping("/editUserInfo")
    public Object editUser(HttpServletRequest request){
        User user = JSON.parseObject(request.getParameter("user"),User.class);
        String tokenKey = request.getHeader("mcsittoken");
        String userUid = tokenService.getTokenValue(tokenKey);
        if (StringUtils.isBlank(user.getUid(),userUid) || user.getUid()!=userUid ){
            return HttpResult.build(HttpResult.ERROR_CODE,"错误");
        }
        boolean success = userService.updateUser(user);
        User resultUser = userService.selectUserByUid(userUid);
        if (!success) return HttpResult.build(HttpResult.ERROR_CODE,"服务器错误");
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("User",resultUser);
        return HttpResult.build(HttpResult.SUCCESS_CODE,resultData,"修改完成");
    }


}
